package org.apache.dubbo.remoting.exchange;

import org.apache.dubbo.common.utils.StringUtils;

import java.util.concurrent.atomic.AtomicLong;

import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;

public class Request {

    private static final AtomicLong INVOKE_ID = new AtomicLong(0);

    private final long id;
    private String version;
    private boolean twoWay = true;
    private boolean event = false;
    private boolean broken = false;
    private Object data;

    public Request() {
        id = newId();
    }

    public Request(long id) {
        this.id = id;
    }

    private static long newId() {
        return INVOKE_ID.getAndIncrement();
    }

    private static String safeToString(Object data) {
        if (data == null) {
            return null;
        }
        String dataStr;
        try {
            dataStr = data.toString();
        } catch (Throwable t) {
            dataStr = "<Fail toString of " + data.getClass() + ", cause: " +
                    StringUtils.toString(t) + ">";
        }
        return dataStr;
    }

    public long getId() {
        return id;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public boolean isTwoWay() {
        return twoWay;
    }

    public void setTwoWay(boolean twoWay) {
        this.twoWay = twoWay;
    }

    public boolean isEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = true;
        this.data = event;
    }

    public void setEvent(boolean event) {
        this.event = event;
    }

    public boolean isBroken() {
        return broken;
    }

    public void setBroken(boolean broken) {
        this.broken = broken;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public boolean isHeartbeat() {
        return event && HEARTBEAT_EVENT == data;
    }

    public void setHeartbeat(boolean isHeartbeat) {
        if (isHeartbeat) {
            setEvent(HEARTBEAT_EVENT);
        }
    }

    @Override
    public String toString() {
        return "Request [id=" + id + ", version=" + version + ", twoway=" + twoWay + ", event=" + event
                + ", broken=" + broken + ", data=" + (data == this ? "this" : safeToString(data)) + "]";
    }
}
